package com.ruoyi.web.controller.marketing;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.domain.ActivityOperationRecord;
import com.ruoyi.system.domain.NewUserRegistrationActivity;
import com.ruoyi.system.domain.RegistrationActivityStore;
import com.ruoyi.system.service.IActivityOperationRecordService;
import com.ruoyi.system.service.INewUserRegistrationActivityService;
import com.ruoyi.system.service.IRegistrationActivityStoreService;
import com.ruoyi.system.util.AbdulEmptyUtils;
import com.ruoyi.system.util.BaseResponse;
import com.ruoyi.system.util.BookingNumberGenerator;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.util.Date;
import java.util.List;

/**
 * 新用户注册活动Controller
 *
 * @author ruoyi
 * @date 2025-06-08
 */
@RestController
@RequestMapping("/system/activity")
@Api(tags = "营销活动-新用户注册有礼")
public class NewUserRegistrationActivityController {

    @Autowired
    private INewUserRegistrationActivityService activityService;

    @Autowired
    private IRegistrationActivityStoreService storeService;

    @Autowired
    private IActivityOperationRecordService recordService;

    /**
     * 查询新用户注册活动列表（分页）
     */
    @GetMapping("/page")
    public BaseResponse<IPage<NewUserRegistrationActivity>> page(@RequestBody NewUserRegistrationActivity activity) {
        Page<NewUserRegistrationActivity> page = new Page<>(activity.getPageNum(), activity.getPageSize());
        LambdaQueryWrapper<NewUserRegistrationActivity> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(!AbdulEmptyUtils.isEmpty(activity.getActivityName()), NewUserRegistrationActivity::getActivityName, activity.getActivityName());
        wrapper.eq(!AbdulEmptyUtils.isEmpty(activity.getActivityCode()), NewUserRegistrationActivity::getActivityCode, activity.getActivityCode());
        wrapper.eq(!AbdulEmptyUtils.isEmpty(activity.getStatus()), NewUserRegistrationActivity::getStatus, activity.getStatus());
        wrapper.eq(!AbdulEmptyUtils.isEmpty(activity.getPhone()), NewUserRegistrationActivity::getPhone, activity.getPhone());
        wrapper.eq(!AbdulEmptyUtils.isEmpty(activity.getStoreId()), NewUserRegistrationActivity::getStoreId, activity.getStoreId());
        wrapper.eq(!AbdulEmptyUtils.isEmpty(activity.getMarketingType()), NewUserRegistrationActivity::getMarketingType, activity.getMarketingType());
        return BaseResponse.success(activityService.page(page, wrapper));
    }


    /**
     * 根据ID查询新用户注册活动详情
     */
    @GetMapping("/{id}")
    public AjaxResult getById(@PathVariable Long id) {
        NewUserRegistrationActivity activity = activityService.getById(id);
        if (AbdulEmptyUtils.isEmpty(activity)) {
            return AjaxResult.error("活动不存在");
        }
        LambdaQueryWrapper<RegistrationActivityStore> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(RegistrationActivityStore::getActivityId, id);
        wrapper.eq(RegistrationActivityStore::getStatus, 1);
        List<RegistrationActivityStore> list = storeService.list(wrapper);
        if (!AbdulEmptyUtils.isEmpty(list)) {
            activity.setStores(list);
        }
        return AjaxResult.success(activity);
    }

    /**
     * 新增新用户注册活动
     */
    @PostMapping("/save")
    public AjaxResult save(@RequestBody NewUserRegistrationActivity activity) {
        if (AbdulEmptyUtils.isEmpty(activity.getValidityPeriodMode())) {
            return AjaxResult.error("请选择有效期方式");
        }
        if (AbdulEmptyUtils.isEmpty(activity.getMarketingType())){
            return AjaxResult.error("请选择营销活动设置类型");
        }
        if (activity.getValidityPeriodMode() == 1) {
            LocalDate now = LocalDate.now();
            activity.setStartDate(now);
            LocalDate futureDate = LocalDate.of(2099, 12, 31);
            activity.setStartDate(futureDate);

        } else if (activity.getValidityPeriodMode() == 2) {
            if (AbdulEmptyUtils.isEmpty(activity.getStartDate()) || AbdulEmptyUtils.isEmpty(activity.getEndDate())) {
                return AjaxResult.error("请选择有效期");
            }
        }
        activity.setActivityCode(BookingNumberGenerator.generateBookingNumber());
        //增加操作记录
        addLog(1, activity);
        boolean result = activityService.save(activity);
        return result ? AjaxResult.success("新增成功") : AjaxResult.error("新增失败");
    }

    /**
     * 更新新用户注册活动
     */
    @PutMapping("/update")
    public AjaxResult update(@RequestBody NewUserRegistrationActivity activity) {
        if (AbdulEmptyUtils.isEmpty(activity.getId())) {
            return AjaxResult.error("请选择要更新的活动");
        }
        NewUserRegistrationActivity registrationActivity = activityService.getById(activity.getId());
        if (AbdulEmptyUtils.isEmpty(registrationActivity)) {
            return AjaxResult.error("修改活动不存在");
        }
        if (!AbdulEmptyUtils.isEmpty(activity.getValidityPeriodMode())) {
            if (activity.getValidityPeriodMode() == 1) {
                LocalDate now = LocalDate.now();
                activity.setStartDate(now);
                LocalDate futureDate = LocalDate.of(2099, 12, 31);
                activity.setStartDate(futureDate);

            } else if (activity.getValidityPeriodMode() == 2) {
                if (AbdulEmptyUtils.isEmpty(activity.getStartDate()) || AbdulEmptyUtils.isEmpty(activity.getEndDate())) {
                    return AjaxResult.error("请选择有效期");
                }
            }
        }
        if (!AbdulEmptyUtils.isEmpty(activity.getActivityName())) {
            registrationActivity.setActivityName(activity.getActivityName());
        }
        if (!AbdulEmptyUtils.isEmpty(activity.getStatus())) {
            registrationActivity.setStatus(activity.getStatus());
        }
        if (!AbdulEmptyUtils.isEmpty(activity.getRemark())) {
            registrationActivity.setRemark(activity.getRemark());
        }
        addLog(2, registrationActivity);
        boolean result = activityService.updateById(registrationActivity);
        return result ? AjaxResult.success("更新成功") : AjaxResult.error("更新失败");
    }

    /**
     * 删除新用户注册活动
     */
    @DeleteMapping("/{id}")
    public AjaxResult delete(@PathVariable Long id) {
        boolean result = activityService.removeById(id);
        return result ? AjaxResult.success("删除成功") : AjaxResult.error("删除失败");
    }


    public void addLog(Integer type, NewUserRegistrationActivity activity){
        ActivityOperationRecord activityOperationRecord = new ActivityOperationRecord();
        activityOperationRecord.setOperationType(type);
        activityOperationRecord.setMarketingActivityCode(activity.getActivityCode());
        activityOperationRecord.setPhone(activity.getPhone());
        activityOperationRecord.setStoreId(activity.getStoreId());
        activityOperationRecord.setCreateBy(SecurityUtils.getUsername());
        activityOperationRecord.setCreateTime(new Date());
        activityOperationRecord.setMarketingType(activity.getMarketingType());
        recordService.save(activityOperationRecord);
    }
}
